import 'package:flutter/material.dart';
import 'package:flutter_demo/common_widget/my_appbar/my_app_bar.dart';
import 'user_model.dart';
import 'package:provider/provider.dart';

class ProviderExample2 extends StatefulWidget {
  ProviderExample2({Key key}) : super(key: key);

  @override
  _ProviderExample2State createState() => _ProviderExample2State();
}

class _ProviderExample2State extends State<ProviderExample2> {
  @override
  Widget build(BuildContext context) {
    print('页面刷新');
    return ChangeNotifierProvider<UserModel>(
        create: (_) => UserModel(),
        child: Scaffold(
            appBar: MyAppBar(title: '这是第一个例子').build(context),
            body: Container(
              height: double.infinity,
              child: ListView(children: [
                Column(
                  children: [
                    Consumer<UserModel>(builder: (_, model, child) {
                      return Text(model.name);
                    }),
                    Count()
                  ],
                ),
              ]),
            )));
  }
}

class Count extends StatelessWidget {
  const Count({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text(

            /// Calls `context.watch` to make [MyHomePage] rebuild when [Counter] changes.
            '${context.watch<UserModel>().name}',
            style: Theme.of(context).textTheme.headline4),
        ElevatedButton(
            child: Text('修改名字'),
            onPressed: () {
              context.read<UserModel>().changeName('我是第二个页面');
            }),
      ],
    );
  }
}
